package api

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"mxshop-api/oss-web/global"
	"mxshop-api/oss-web/utils/aliyun"
)

func Token(c *gin.Context) {
	response := aliyun.GetPolicyToken()
	c.Header("Access-Control-Allow-Methods", "POST")
	c.Header("Access-Control-Allow-Origin", "*")
	c.String(200, response)
}

func CallBack(c *gin.Context) {
	// Get PublicKey bytes
	bytePublicKey, err := aliyun.GetPublicKey(c)
	if err != nil {
		responseFailed(c)
		return
	}

	// Get Authorization bytes : decode from Base64String
	byteAuthorization, err := aliyun.GetAuthorization(c)
	if err != nil {
		responseFailed(c)
		return
	}

	// Get MD5 bytes from Newly Constructed Authorization String.
	byteMD5, err := aliyun.GetMD5FromNewAuthString(c)
	if err != nil {
		responseFailed(c)
		return
	}

	// verifySignature and response to client
	if !aliyun.VerifySignature(bytePublicKey, byteMD5, byteAuthorization) {
		responseFailed(c) // response FAILED : 400
		return
	}

	// do something you want according to callback_body ...
	c.JSON(http.StatusOK, gin.H{
		"url": global.ServerConfig.OSSConfig.Host + "/" + c.PostForm("filename"),
	})
}

func responseFailed(c *gin.Context) {
	c.Status(http.StatusBadRequest)
}
